var uls = document.getElementById("paylistway");
var allloaded = false;
showLoading();
mui.back = function() {
		delete localStorage.fastway;
		delete localStorage.selectobj;
		plus.webview.currentWebview().close();
	}
	//确认订单控制器
function orders($scope, $http) {
	//读取订单临时缓存：1 由购物车页面生成的缓存；2修改地址、物流或发票后，调整的缓存
	orders = eval('(' + readData(localStorage.order) + ')');
	var allPay = 0;
	var products;
	//取后台快递下拉列表值
	wuliu = "yes"
	urlkd = getUrl("28kuaidi");
	headerkd = getHeader();
	paramskd = 'userId=' + readData(localStorage.guideId)
	$http({
		method: 'POST',
		url: urlkd,
		headers: headerkd,
		timeout: 10000,
		data: paramskd
	}).success(function(data, status, headers, config) {
		if (data.obj) {
			$scope.kuaidis = data.obj.list;
			$scope.kdSelected = $scope.kuaidis[0];
		} else {

			$scope.kuaidis = [];
			$scope.kdSelected = $scope.kuaidis[0];
			//后台获取code==2表示没有物流
			if (data.code == 2) {
				wuliu = "no";
				document.getElementById("fastway").style.display = "none"
			}
		};
		$scope.getKD();
	}).error(function(data, status, headers, config) {
		$scope.kuaidis = [];
		$scope.kdSelected = $scope.kuaidis[0];
		console.log("获取物流出错")
		$scope.getKD();
	});
	$scope.getKD = function() {
			//取地址默认值
			//判断是否设置地址
			if (orders.address == "" || orders.address == "undefined" || orders.address == null) {
				//运送方式
				$scope.carry = 1;
				//地址
				$scope.address = null;
				//费用
				$scope.freight = 0;
				//从后台获取用户默认地址
				urldz = getUrl("22address");
				headerdz = getHeader();
				paramsdz = 'accountId=' + readData(localStorage.account) + '&defaultAddr=y';
				$http({
					method: 'POST',
					url: urldz,
					headers: headerdz,
					timeout: 10000,
					//cache: true,
					data: paramsdz
				}).success(function(data, status, headers, config) {
					if (data.obj) {
						$scope.address = data.obj.list[0];
					} else {
						$scope.address = null;
					};
				}).error(function(data, status, headers, config) {
					console.log("获取默认地址失败")
				});
				$scope.applypayAmount();
			} else {
				//获取用户修改的地址
				$scope.carry = 2;
				$scope.address = orders.address;
				if (!$scope.kuaidis)
					($scope.kuaidis = [{
						name: '默认快递',
						fee: '0'
					}]);
				$scope.kdSelected = $scope.kuaidis[0];
				$scope.freight = $scope.kdSelected.fee;
				document.getElementById("way").checked = true;
				document.getElementById("address").style.display = "block";
				if (localStorage.fastway) {
					$scope.kdSelected = $scope.kuaidis[readData(localStorage.fastway)];
					$scope.freight = $scope.kdSelected.fee;
					delete localStorage.fastway;
				}
				$scope.applypayAmount();
			}
			//发票信息
			if (orders.invoice == "" || orders.invoice == "undefined" || orders.invoice == null) {
				$scope.invoice = {
					type: '',
					head: '',
					content: ''
				};
				document.getElementById("first").style.lineHeight = 65 + "px";
			} else {
				$scope.invoice = orders.invoice
			}
			//获取商品信息
			//var produ = orders.list;
			goodList = orders.list;
			for (var obj in goodList) {
				var exchangePrice = 0;
				if (goodList[obj].exchangeList) {
					for (var j in goodList[obj].exchangeList) {
						exchangePrice += parseFloat(goodList[obj].exchangeList[j].price);
					}
				}
				goodList[obj].priceall = (parseFloat(goodList[obj].nowPrice) * parseFloat(goodList[obj].number) + exchangePrice).toFixed(2);
				goodList[obj].totalPay = goodList[obj].priceall
				if (!goodList[obj].deposit) {
					goodList[obj].showmoney = false;
				} else {
					goodList[obj].showmoney = true;
				}
			}
			$scope.goodsList = goodList;
			//products = orders.list;暂时修改
			products = goodList;
			//计算数量金额
			var num = 0;
			var mon = 0;
			for (var i = 0; i < products.length; i++) {
				var goods = products[i];
				num = num + parseFloat(goods.number);
				//mon = mon + parseFloat(goods.number) * parseFloat(goods.nowPrice);
				mon += parseFloat(goods.priceall)
			}
			//商品数量
			$scope.sumNum = num;
			//没有加邮费折扣的商品总金额即订单总额
			$scope.sumMon = mon.toFixed(2);
			//$scope.money = (parseFloat($scope.sumMon) + parseFloat($scope.freight)).toFixed(2);
		}
		//从后台获取付款模式
	modelUrl = getUrl("71findPayModels");
	modelHeader = getHeader();
	listpro = [];
	modelList = orders.list
	for (var obj in modelList) {
		listpro.push({
			id: modelList[obj].id,
			name: modelList[obj].name,
			number: modelList[obj].number,
			specColorpr: modelList[obj].specColorpr,
			specSizepr: modelList[obj].specSizepr,
			specSpec: modelList[obj].specSpec,
			specModel: modelList[obj].specModel,
			giftList: modelList[obj].giftList,
			exchangeList: modelList[obj].exchangeList
		});
	}
	paramModel = 'json={"listpro":' + JSON.stringify(listpro) + '}'
	$scope.applypayAmount = function() {
			$http({
				method: 'POST',
				url: modelUrl,
				headers: modelHeader,
				timeout: 10000,
				data: paramModel
			}).success(function(data, status, headers, config) {
				var bhandsel = bdelivery = false;
				if (data.obj) {
					allloaded = true;
					//折扣
					$scope.discount = data.obj.discount;
					//立减
					$scope.reduceAmount = data.obj.reduceAmount;
					//订单总额
					$scope.money = (parseFloat($scope.sumMon) + parseFloat($scope.freight) - parseFloat($scope.discount) - parseFloat($scope.reduceAmount)).toFixed(2);
					//付款服饰
					models = data.obj.payModels;
					for (var i in models) {
						if (models[i].code == "3") {
							//全额支付
							$scope.allPay = parseFloat(models[i].payAmount);
							//商品全额支付列表
							$scope.allpaylists = models[i].list;
							if (!localStorage.selectobj) {
								$scope.allpay($scope.allpaylists, $scope.allPay, '3');
							} else {
								var json = eval('(' + readData(localStorage.selectobj) + ')');
								$scope.allpay(json.alllist, json.pay, json.domId);
								change(json.domId)
							}
						}
						if (models[i].code == "1") {
							//定金支付
							bhandsel = true;
							$scope.handsellists = models[i].list;
							$scope.handselPay = parseFloat(models[i].payAmount);
						}
						if (models[i].code == "2") {
							//货到付款
							bdelivery = true;
							//document.getElementById("2").style.display="block";
							$scope.deliverylists = models[i].list;
							$scope.deliveryPay = parseFloat(models[i].payAmount);
						}
					}
					var li1 = document.getElementById("1");
					var li2 = document.getElementById("2");
					if (bhandsel) {
						li1.style.display = "inline-block";
					} else {
						uls.removeChild(li1);
					}
					if (bdelivery) {
						li2.style.display = "inline-block";
					} else {
						uls.removeChild(li2);
					}

				}
				removeLoading()
			}).error(function(data, status, headers, config) {
				removeLoading()
				mui.toast("网络异常，请稍后重试")
			});
		}
		/*商品应付控制全额，定金，货到付款的页面操作
		 * arr商品应付列表
		 * pay不同付款模式应付金额 （没有加邮费，折扣，立减的）
		 * did代表不同的模式
		 */
	$scope.allpay = function(arr, pay, dId) {
			$scope.oldPay = pay;
			//应付金额
			$scope.shouldPay = (pay + parseFloat($scope.freight) - parseFloat($scope.discount)).toFixed(2);
			var arrlist = $scope.goodsList;
			for (var obj in arrlist) {
				for (var index in arr) {
					if ((arrlist[obj].id + arrlist[obj].specColorpr + arrlist[obj].specSizepr + arrlist[obj].specSpec + arrlist[obj].specModel) == (arr[index].id + arr[index].specColor + arr[index].specSize + arr[index].specSpec + arr[index].specModel)) {
						arrlist[obj].totalPay = arr[index].payAmount;
						if (dId == "3") {
							arrlist[obj].giftList = arr[index].giftList;
						}
					}
				}
			}
			//存储选择不同模式的选项
			selectjson = {
				"alllist": arr,
				"pay": pay,
				"domId": dId
			}
			$scope.paymodelId = dId;
			localStorage.selectobj = writeData(JSON.stringify(selectjson));
			$scope.goodsList = arrlist;
		}
		//自提时候操作
	$scope.hid = function() {
			$scope.carry = '1';
			document.getElementById("address").style.display = "none";
			delete orders["address"];
			$scope.freight = 0;
			$scope.money = (parseFloat($scope.sumMon) + parseFloat($scope.freight) - parseFloat($scope.discount) - parseFloat($scope.reduceAmount)).toFixed(2);
			$scope.shouldPay = ($scope.oldPay + parseFloat($scope.freight) - parseFloat($scope.discount)).toFixed(2)
			localStorage.order = writeData(JSON.stringify(orders));
		}
		//物流操作
	$scope.show = function() {
			if (wuliu == "no") {
				mui.alert("商户没有可使用的快递");
				return;
			}
			$scope.carry = '2';
			document.getElementById("address").style.display = "block";
			//更新地址快递信息，保存快递信息
			orders['address'] = $scope.address;
			if ($scope.kuaidis) {
				if ($scope.kuaidis[0]) {
					$scope.kdSelected = $scope.kuaidis[0];
					$scope.freight = $scope.kdSelected.fee;
				} else {
					$scope.freight = 0;
				}
			} else {
				$scope.freight = 0;
			}
			$scope.money = (parseFloat($scope.sumMon) + parseFloat($scope.freight) - parseFloat($scope.discount) - parseFloat($scope.reduceAmount)).toFixed(2);
			$scope.shouldPay = ($scope.oldPay + parseFloat($scope.freight) - parseFloat($scope.discount)).toFixed(2)
			localStorage.order = writeData(JSON.stringify(orders));
		}
		//物流变更时，修改快递费用及总金额
	$scope.kdAlter = function() {
			$scope.freight = $scope.kdSelected.fee;
			$scope.money = (parseFloat($scope.sumMon) + parseFloat($scope.freight) - parseFloat($scope.discount) - parseFloat($scope.reduceAmount)).toFixed(2);
			$scope.shouldPay = ($scope.oldPay + parseFloat($scope.freight) - parseFloat($scope.discount)).toFixed(2)
		}
		//修改地址方法
	$scope.alterAddress = function() {
			for (var i in $scope.kuaidis) {
				if ($scope.kuaidis[i].id == $scope.kdSelected.id) {
					localStorage.fastway = writeData(i);
				}
			}
			OpenNewWin({
				url: "../../html/shopping/conformAddress.html",
				id: "conformAddress.html"
			})
		}
		//修改发票方法：保存order信息，打开新窗口
	$scope.alterInvoice = function() {
			for (var i in $scope.kuaidis) {
				if ($scope.kuaidis[i].id == $scope.kdSelected.id) {
					localStorage.fastway = writeData(i);
				}
			}
			localStorage.order = writeData(JSON.stringify(orders));
			OpenNewWin({
				url: "../../html/shopping/conformInvoice.html",
				id: "conformInvoice.html"
			})
		}
		//订单提交
	$scope.orderSubmit = function() {
		if (!allloaded) return;
		urlDd = getUrl("25orderCreate");
		headerDd = getHeader();
		var prolist = [];
		var idList = [];
		//将当前产品信息获取，保存到订单参数
		for (var i = 0; i < products.length; i++) {
			productInfo = products[i];
			//delete productInfo['picture'];
			if (productInfo['id']) {
				productInfo['productId'] = productInfo['id'];
			} else {
				productInfo['id'] = productInfo['productId'];
			}
			idList[i] = productInfo['id'];
			delete productInfo['id'];
			prolist.push(productInfo);
		};
		if ($scope.carry == 2) {
			if ($scope.kdSelected) {
				if ($scope.address) {
					paramsDd = {
						invoiceType: $scope.invoice['type'], //发票类型
						invoiceHead: $scope.invoice['head'], //发票抬头
						invoiceContent: $scope.invoice['content'], //发票内容
						fee: $scope.freight,
						guideId: readData(localStorage.guideId),
						quantity: $scope.sumNum,
						otherRequirement: '无', //附加要求
						account: readData(localStorage.phone),
						carry: $scope.carry, //运送方式
						ordershipId: orders.address['id'], //收货地址ID
						expressCompanyName: $scope.kdSelected['name'], //快递公司名称
						//	payModelAmount : $scope.money,
						payModelAmount: $scope.oldPay,
						bcPayAmount: $scope.shouldPay,
						payModel: $scope.paymodelId,
						listpro: prolist
					}
					var datas = "json=" + JSON.stringify(paramsDd);
					plus.nativeUI.showWaiting("正在提交…")
					$http({
						method: 'POST',
						url: urlDd,
						headers: headerDd,
						timeout: 10000,
						//cache: true,
						data: datas
					}).success(function(data, status, headers, config) {
						if (data.msg == 'success') {
							//删除购物车商品
							if (!orders['ljgm']) {
								for (var i = 0; i < products.length; i++) {
									var productInfo = products[i];
									goodsDel(idList[i], readData(localStorage.guideId), productInfo.specSizepr, productInfo.specColorpr, productInfo.specModel, productInfo.specSpec);
								}
								//刷新购物车数量
								refershBycar();
							}
							//存入金额、订单号
							//orders['orderNo'] = data.orderNo;
							orders['orderNumber'] = data.orderNo;
							orders['orderId'] = data.orderId;
							orders['marketId'] = data.marketId;
							//orders['mon'] = $scope.money;
							orders['amount'] = $scope.money;
							orders['quantity'] = $scope.sumNum;
							orders['fee'] = $scope.freight;
							orders['shouldPay'] = $scope.shouldPay;
							localStorage.order = writeData(JSON.stringify(orders));
							delete localStorage.fastway;
							delete localStorage.selectobj;
							//进入订单支付页面
							if (data.status == "init") {
								localStorage.conformOrder = "true";
								openOrderPay();
							} else {
								openOrderPaySuccess();
							}
						} else {
							mui.toast("网络连接异常，请稍后重试" + data.code)
						};
						plus.nativeUI.closeWaiting();
					}).error(function(data, status, headers, config) {
						mui.toast("网络连接异常，请稍后重试(e)")
						plus.nativeUI.closeWaiting();
					});
				} else {
					mui.toast("请填写收货地址信息")
				}
			} else {
				mui.toast("暂不支持快递，请选择自提");
			}
		} else {
			paramsDd = {
				invoiceType: $scope.invoice['type'], //发票类型
				invoiceHead: $scope.invoice['head'], //发票抬头
				invoiceContent: $scope.invoice['content'], //发票内容
				fee: $scope.freight,
				guideId: readData(localStorage.guideId),
				quantity: $scope.sumNum,
				otherRequirement: '无', //附加要求
				account: readData(localStorage.phone),
				carry: $scope.carry, //运送方式
				ordershipId: '', //收货地址ID
				expressCompanyName: '', //快递公司名称
				//payModelAmount : $scope.money,
				payModelAmount: $scope.oldPay,
				bcPayAmount: $scope.shouldPay,
				payModel: $scope.paymodelId,
				listpro: prolist
			}
			var datas = "json=" + JSON.stringify(paramsDd);
			plus.nativeUI.showWaiting("正在提交…")
			$http({
				method: 'POST',
				url: urlDd,
				headers: headerDd,
				timeout: 10000,
				//cache: true,
				//params: paramsDd
				data: datas
			}).success(function(data, status, headers, config) {
				if (data.msg == 'success') {
					//删除购物车商品
					if (!orders['ljgm']) {
						for (var i = 0; i < products.length; i++) {
							var productInfo = products[i]
							goodsDel(idList[i], readData(localStorage.guideId), productInfo.specSizepr, productInfo.specColorpr, productInfo.specModel, productInfo.specSpec);
						}

						//刷新购物车数量
						refershBycar();
					}
					//存入金额、订单号
					//orders['orderNo'] = data.orderNo;
					orders['orderNumber'] = data.orderNo;
					orders['orderId'] = data.orderId;
					orders['marketId'] = data.marketId;
					//orders['mon'] = $scope.money;
					orders['amount'] = $scope.money;
					orders['quantity'] = $scope.sumNum;
					orders['fee'] = $scope.freight;
					orders['shouldPay'] = $scope.shouldPay;
					localStorage.order = writeData(JSON.stringify(orders));
					delete localStorage.selectobj;
					//进入订单支付页面
					if (data.status == "init") {
						localStorage.conformOrder = "true";
						openOrderPay();
					} else {
						openOrderPaySuccess();
					}
				} else {
					mui.toast("网络连接异常，请稍后重试" + data.code);
				};
				plus.nativeUI.closeWaiting()
			}).error(function(data, status, headers, config) {
				mui.toast("网络连接异常，请稍后重试(e)")
				plus.nativeUI.closeWaiting();
			});
		};
	}
}

function change(thisId) {
	var lis = uls.getElementsByTagName("li");
	for (var i = 0; i < lis.length; i++) {
		lis[i].className = "";
	}
	document.getElementById(thisId).className = "active";
}
window.addEventListener("reload", function() {
	window.location.reload();
},false)